﻿using ACC.Business.Stn;
using ACC.Business.Utils;
using ACC.Data;
using ACC.Data.ACCLog;
using ACC.Data.Comm;
using ACC.Data.Entities.Mes;
using ACC.Data.Line;
using ACC.Device;
using ACC.Device.PLC.Siemens;
using ACC.LineDevice.KukaPack;
using ACC.Util.Convert;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;



namespace Script
{
    /// <summary>
    /// 电芯上料，OP L1M01030, STN L1M11031, L1M21031
    /// 6个电芯同时load/unload，以ProcessData中Name中含“结果”的值判断
    /// 若值为0，IsOK=True；若值大于0，IsOK=False；
    /// 在load时将[ACC_BATTERY_DATA]表中电压内阻的上下限发送给PLC
    /// TO-DO: 增加6个电芯是同一批次(在订单批次里，订单批次可能有多个，以";"分隔)的检查，报警
    /// </summary>
    public class L1M01030 : StnProcessPL02_DX
    {
        public L1M01030(StnRunningData data)
            : base(data)
        {
        }

        protected override ACCDevice CreateDevice()
        {
            ACCDevice dev = base.CreateDevice();
            if (kukaSiemensDev != null)
            {
                switch (_data.StnCfg.Name)
                {
                    case "L1M11031":
                        {
                            kukaSiemensDev.DB190_Offset = 0;
                        }
                        break;
                    case "L1M21031":
                        {
                            kukaSiemensDev.DB190_Offset = 3000;
                        }
                        break;
                }

                kukaSiemensDev.DB190 = 800;
                kukaSiemensDev.DB192 = 80;
                kukaSiemensDev.DB192_PLC_Offset = (ushort)(kukaSiemensDev.DB190_Offset + 258);
                kukaSiemensDev.DB193 = 800;
                kukaSiemensDev.DB193_PLC_Offset = (ushort)(kukaSiemensDev.DB190_Offset + 34);
                kukaSiemensDev.DB193_ACC_Offset = (ushort)(kukaSiemensDev.DB190_Offset + 68);
                kukaSiemensDev.DB194 = 800;
                kukaSiemensDev.DB194_PLC_Offset = (ushort)(kukaSiemensDev.DB190_Offset + 34);
                kukaSiemensDev.DB194_PLC_Data_Offset = kukaSiemensDev.DB190_Offset + 270;
                // TO-DO: 感觉这里应该是 260
                kukaSiemensDev.Material_COMM_Offset = 260; //260， 3260 上下料信号位偏移量
                kukaSiemensDev.BarcodeLength = 30;
                kukaSiemensDev.LoadBarcodeCount = 6;
                kukaSiemensDev.UnloadBarcodeCount = 6;
            }

            return dev;

        }

        protected override void CreateBusinessLogic()
        {
            base.CreateBusinessLogic();

            (_loadProcess as LoadProcess_DX).R = 1;
            (_unloadProcess as UnloadProcess_DX).R = 1;
            (_unloadProcess as UnloadProcess_DX).OneAsNG = true;

            //_womsProcess = new iPlant.Features.WOMSClient.Business.WOMSClientForSqlServer(_data, Device);
        }

        public override void ChangePartNo(RuningPartNo newpartno)
        {
            base.ChangePartNo(newpartno);

            if (newpartno != null)
            {
                var v = _data.PartNo.BomCfg.GetBomItemCfgByIDName("电芯").Clone();
                v.QtyPer = 1;

                _data.Components = new BomItemCfg[] { v };
            }
        }

        /// <summary>
        /// 进站的时候检查6个电芯是否是同一批，不是同一批报警
        /// </summary>
        /// <param name="dev"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public override ACCCode ReadLoadParam(ACCDevice dev, out ACCDevice.LoadParam param)
        {
            ACCCode code = base.ReadLoadParam(dev, out param);

            if (code == ACCCode.ACCOK)
            {
                string[] barcodes = new string[] { param.UnitSN };
                var v = barcodes.Concat(param.ComponentSN);
                string[] aryLot = new string[v.Count()];
                string partNo, orderNo;
                int planQty;
                GetWorkOrder(_lineData.Line, string.Empty, out partNo, out orderNo, out planQty);
                string orderLot = GetOrderCellLot(orderNo);
                foreach (string unitsn in v)
                {
                    if (string.IsNullOrEmpty(unitsn) || string.IsNullOrEmpty(unitsn.Trim()) || unitsn.Trim().ToUpper() == "NG")
                        continue;

                    if (!CheckCellLot(orderLot, GetBatteryLot(unitsn)))
                    {
                        code = ACCCode.UserDef_113;       // 电芯批次号不一致
                        break;
                    }
                }

                param.PartTypeID = _data.PartNo == null ? 0 : (int)_data.PartNo.BomCfg.PartTypeID;
                param.PartNo = _data.PartNo;
            }

            return code;
        }

        public override ACCCode SendLoadResult(ACCDevice dev, ACCDevice.LoadResult result)
        {
            if (result.ErrorCode == ACCCode.ACCOK && _data.LastLoadUnit != null)
            {
                // 新需求，写入电芯批次给PLC
                string cellLot = GetBatteryLot(_data.LastLoadUnit.UnitSN); // 根据电芯码获取电芯批次
                // TO-DO: 确定写入地址
                SendBarcodeToPlc(new string[] { cellLot }, kukaSiemensDev.DB190_Offset + 2, 30); //  kukaSiemensDev.DB190_Offset + 2

                // TO-DO: 一次性获取一次性写入PLC，否则有性能问题
                GetAndSendLimitsToPlc(_data.LastLoadUnit.UnitSN);
            }

            return base.SendLoadResult(dev, result);
        }

        /// <summary>
        /// 获取电芯的参数并写入PLC指定地址位（连续）
        /// </summary>
        /// <param name="UnitSN"></param>
        /// <returns></returns>
        public bool GetAndSendLimitsToPlc(string unitSN)
        {
            bool bRet = false;

            // 新需求，写入上下限给PLC （应考虑更好方案）
            string sql = string.Format("SELECT * FROM [YuTong_ACC].[dbo].[ACC_BATTERY_DATA] where BARCODE='{0}'", unitSN);
            DataTable dt = DataManager.DBHelper.Query(sql);
            if (dt != null && dt.Rows.Count > 0)
            {
                List<float> lstLimits = new List<float>();
                lstLimits.Add(Convert.ToSingle(dt.Rows[0]["VOLTAGEUPPERLIMIT"].ToString()));
                lstLimits.Add(Convert.ToSingle(dt.Rows[0]["VOLTAGELOWERLIMIT"].ToString()));
                lstLimits.Add(Convert.ToSingle(dt.Rows[0]["RESISTANCEUPPERLIMIT"].ToString()));
                lstLimits.Add(Convert.ToSingle(dt.Rows[0]["RESISTANCELOWERLIMIT"].ToString()));

                //将条码电芯内阻电压写入指定DB地址（如：DB193.startPos对应800.34）,发给PLC
                bRet = SendRealToPlc(lstLimits.ToArray(), kukaSiemensDev.DB190_Offset + 390) == ACCCode.ACCOK ? true : false;
            }
            return bRet;
        }
        public bool CheckCellLot(string orderLot, string currentLot)
        {
            if (!string.IsNullOrEmpty(orderLot) && !string.IsNullOrEmpty(currentLot))
            {
                foreach (string lot in orderLot.Split(';'))
                {
                    if (currentLot == lot)
                        return true;
                }
            }
            return false;
        }

    }
}
